#!/usr/bin/env node

//jpg binary image file ==> base64 string

const fs = require('fs'),
  http = require('http'),
  path = require('path'),
  file = process.argv[2];

if(process.argv.length !== 3) {
 
  console.error('命令行参数格式：cmd fileName');
  process.exit(1);
}
//文件不存在，抛出异常
try{

  var data = fs.readFileSync(file).toString('base64');
}catch(e){
  console.error(e.message);
  process.exit(2);
}

let ext = path.extname(file);
let uriData = 'data:image/' + ext.slice(1,ext.length) + ';base64,' + data;


////文件=>base64?
//const buf = fs.readFileSync('./qr-code.jpg');
//const img_base64 = buf.toString('base64');

//console.log(buf);
//console.log(buf.toString('base64'));

//const html = `<!doctype html><html><body><img src="data:image/jpg;base64,${img_base64}"></body></html>`;

let html = `
  <!DOCTYPE html>
  <html>
    <head><title>base64 demo</title></head>
    <body>
    <img alt="${path.basename(file,ext)}" src="${uriData}">
    </body>
  </html>`;

http.createServer((req, res) => {
  console.log(req.headers);
  console.log(req.url +'\n');
  res.end(html);
}).listen(8080);

//./04-data-url.js qr-code.jpg
